<template>
  <div class="container-box">
    <!--筛选表单-->
    <div class="filter-form">
      <el-row type="flex" justify="space-between">
        <el-form ref="form" label-width="50px" :inline="true" size="small">
          <el-form-item>
            <el-input
              ref="input"
              v-model="queryData.class_name"
              placeholder="班级名称"
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item>
            <el-select v-model="queryData.subject_id" placeholder="归属学科">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-select
              v-model="queryData.state"
              clearable
              size="small"
              placeholder="显示状态"
            >
              <el-option label="显示" :value="1" />
              <el-option label="隐藏" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-search"
              type="primary"
              plain
              @click="onSearch"
            >搜索</el-button>
            <el-button icon="el-icon-refresh" @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>

        <div>
          <el-button type="primary" size="small" plain @click="flag=true">创建班级</el-button>
        </div>
      </el-row>

    </div>

    <!--表单区域-->
    <el-table
      :data="list"
      style="width: 100%"
      border
      :header-cell-style="{ background: '#fafafa', color: '#646464' }"
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="班级名称">
              <span>{{ props.row.class_name }}</span>
            </el-form-item>
            <el-form-item label="归属学科">
              <span>{{ props.row.subject_name }}</span>
            </el-form-item>
            <el-form-item label="创建人">
              <span>{{ props.row.username }}</span>
            </el-form-item>
            <el-form-item label="开始结束日期">
              <span>{{ formatTime(props.row.start_time) }}至{{ formatTime(props.row.end_time ) }}</span>
            </el-form-item>
            <el-form-item label="创建日期">
              <span>{{ props.row.created_at }}</span>
            </el-form-item>
            <el-form-item label="讲师">
              <el-button
                v-for="(item,i) in JSON.parse(props.row.teacher_info)"
                :key="i"
                style="margin-left:20px"
                type="primary"
                size="small"
                plain
              >{{ item.username }}</el-button>
            </el-form-item>
            <el-form-item label="助教">
              <el-button
                v-for="(item,i) in JSON.parse(props.row.zhujiao_info)"
                :key="i"
                size="small"
                style="margin-left:20px"
                type="success"
                plain
              >{{ item.username }}</el-button>
            </el-form-item>
            <el-form-item label="讲师">
              <el-button
                v-for="(item,i) in JSON.parse(props.row.manager_info)"
                :key="i"
                style="margin-left:20px"
                type="primary"
                size="small"
                plain
              >{{ item.username }}</el-button>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column label="#" width="50" />
      <el-table-column
        type="index"
        label="序号"
        width="80"
        align="center"
      />
      <el-table-column
        prop="id"
        label="班级ID"
        width="80"
        align="center"
      />
      <el-table-column
        prop="class_name"
        label="班级名称"
      />
      <el-table-column
        prop="subject_name"
        label="归属学科"
      />
      <el-table-column
        label="讲师"
        width="100"
        align="center"
      >
        <template slot-scope="{row}">
          <el-button
            v-for="(item) in JSON.parse(row.teacher_info)"
            :key="item.user_id"
            style="margin-bottom:5px"
            type="primary"
            size="small"
            plain
          >{{ item.username }}</el-button>
        </template>
      </el-table-column>

      <el-table-column
        label="助教"
        width="100"
        align="center"
      >
        <template slot-scope="{row}">
          <el-button
            v-for="(item) in JSON.parse(row.zhujiao_info)"
            :key="item.user_id"
            style="margin-bottom:5px"
            size="small"
            type="success"
            plain
          >{{ item.username }}</el-button>
        </template>
      </el-table-column>

      <el-table-column
        label="班主任"
        width="100"
        align="center"
      >
        <template slot-scope="{row}">
          <el-button
            v-for="(item) in JSON.parse(row.manager_info)"
            :key="item.user_id"
            style="margin-bottom:5px"
            size="small"
            type="warning"
            plain
          >{{ item.username }}</el-button>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        prop="username"
        label="创建人"
        width="140"
      />

      <el-table-column
        align="center"
        prop="state"
        label="是否显示"
        width="120"
      >
        <template slot-scope="{ row }">
          <el-switch
            v-model="row.state"
            active-text="是"
            inactive-text="否"
            :active-value="1"
            :inactive-value="2"
            @change="switchChange($event, row.id)"
          />
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        prop="state"
        label="开始结束日期"
        width="200"
      >
        <template slot-scope="{ row }">
          <span>{{ formatTime(row.start_time ) }}至{{ formatTime(row.end_time ) }}</span>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        prop="created_at"
        label="创建日期"
        width="200"
      />

      <el-table-column
        align="center"
        label="操作"
        fixed="right"
        width="200"
      >
        <template slot-scope="{ row }">
          <el-button
            size="small"
            type="primary"
            icon="el-icon-edit"
            circle
            @click="onEdit(row.id)"
          />
          <el-button
            size="small"
            type="danger"
            icon="el-icon-delete"
            circle
            @click="onDelete(row.id)"
          />
        </template>
      </el-table-column>
    </el-table>
    <!--分页区域-->
    <div class="page">
      <el-pagination
        :current-page.sync="queryData.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryData.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
        @size-change="sizeChange"
        @current-change="currentChange"
      >
        :pager-count="7">
      </el-pagination>
    </div>

    <!-- =============================新增 -->
    <el-dialog
      :title="`${title}班级`"
      :visible.sync="flag"
      width="45%"
      @close="onCancel"
    >
      <el-form
        ref="form"
        :model="formData"
        :rules="rules"
        label-width="100px"
        :inline="true"
        size="normal"
      >
        <el-form-item label="归属学科" prop="subject_id" label-width="100px">
          <el-select
            v-model="formData.subject_id"
            placeholder="请选择"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班级名称" prop="class_name">
          <el-input
            v-model="formData.class_name"
            placeholder="请输入班级名称"
            size="small"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="授课老师" label-width="100px">
          <el-select
            v-model="formData.teacher_info"
            value-key="user_id"
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="item in teacher"
              :key="item.user_id"
              :label="item.username"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="助教老师" label-width="100px">
          <el-select
            v-model="formData.zhujiao_info"
            value-key="user_id"
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="item in zhujiao"
              :key="item.user_id"
              :label="item.username"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班主任老师" label-width="100px">
          <el-select
            v-model="formData.manager_info"
            value-key="user_id"
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="item in manager"
              :key="item.user_id"
              :label="item.username"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开课节课日期" prop="status">
          <el-date-picker
            v-model="timeList"
            style="width:200px"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="changeTime"
          />
        </el-form-item>
        <el-form-item label="排序" prop="role_id">
          <el-input-number
            v-model="formData.sort"
            style="width:200px"
            :min="1"
            :max="10"
            label="描述文字"
          />
        </el-form-item>

        <el-form-item label="班级状态" label-width="100px">
          <el-switch
            v-model="formData.state"
            active-text="正常"
            inactive-text="关闭"
            :active-value="1"
            :inactive-value="2"
          />
        </el-form-item>
      </el-form>
      <el-row type="flex" justify="end">
        <el-button size="small" @click="flag = false">取消</el-button>
        <el-button
          type="primary"
          size="small"
          @click="onSubmit"
        >确定</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getClassApi, getSubjectApi, getSwitchApi, getTeacherApi, addClassApi, delClassApi, showClassApi, editClassApi } from '@/api/class'
import moment from 'moment'
export default {
  name: 'TagList',
  data() {
    return {
      timeList: [],
      // 表格数据
      list: [],
      // 查询参数
      queryData: {
        page: 1,
        limit: 10,
        class_name: '',
        state: '',
        subject_id: '' // 学科
      },
      options: [],
      total: 0,
      // 弹框控制变量
      flag: false,
      // 表单控制变量
      formData: {
        class_name: '',
        end_time: '',
        manager_info: [],
        sort: 10,
        start_time: '',
        state: 1,
        subject_id: '',
        teacher_info: [],
        zhujiao_info: []
      }, // 表单数据
      // 表单验证规则变量
      rules: {
        subject_id: [{ required: true, message: '请选择学科分类', trigger: 'blur' }],
        class_name: [{ required: true, message: '请输入班级名称', trigger: 'blur' }]
      },
      teacher: [], // 讲师
      manager: [], // 班主任
      zhujiao: [] // 助教
    }
  },
  computed: {
    title() {
      return this.formData.id ? '修改' : '新增'
    }
  },
  async created() {
    this.initData()
    this.getTeacherList()
    const res = await getSubjectApi()
    // console.log(res)
    this.options = res
  },
  methods: {
    // 初始化表格数据
    async initData() {
      // 调用API函数获取表格数据
      const res = await getClassApi(this.queryData)
      // console.log(res)
      // 赋值变量
      this.list = res.list
      this.total = res.total
      // console.log(JSON.parse(this.list[0].teacher_info))
      // console.log(this.list.map(item => JSON.parse(item.teacher_info)).map(item => item.map(item => item.username)))
    },
    // 筛选表单搜索提交
    onSearch() {
      this.queryData.page = 1
      this.initData()
    },
    // 筛选表单重置
    onReset() {
      this.queryData = {
        page: 1,
        limit: 10,
        class_name: '',
        state: '',
        subject_id: '' // 学科
      }
      this.initData()
    },
    // 每页数量切换事件
    sizeChange(val) {
      this.queryData.limit = val
      this.initData()
    },
    // 页码切换事件
    currentChange(val) {
      this.queryData.page = val
      this.initData()
    },
    // ============================新增
    async onSubmit() {
      // 表单校验
      await this.$refs.form.validate()
      // 发送请求
      this.formData.id ? await editClassApi(this.formData) : await addClassApi(this.formData)
      // 消息提示

      this.$message.success(this.formData.id ? '修改成功' : '添加成功')
      // 关闭弹框
      this.flag = false
      // 更新列表
      this.initData()
    },
    onCancel() {
      // 表单重置
      this.formData = {
        class_name: '',
        end_time: '',
        manager_info: [],
        sort: 10,
        start_time: '',
        state: 1,
        subject_id: '',
        teacher_info: [],
        zhujiao_info: []
      }
      // 移除校验
      this.$refs.form.clearValidate()
    },
    // ============================修改
    async onEdit(id) {
      // 获取该行数据
      const res = await showClassApi(id)
      // console.log(res)
      // 赋值给表单变量
      this.formData = res
      this.formData.teacher_info = JSON.parse(res.teacher_info)
      this.formData.manager_info = JSON.parse(res.manager_info)
      this.formData.zhujiao_info = JSON.parse(res.zhujiao_info)
      this.formData.start_time = moment(res.start_time).format('YYYY-MM-DD')
      this.formData.end_time = moment(res.end_time).format('YYYY-MM-DD')
      // console.log(this.formData.start_time)
      this.timeList = [this.formData.start_time, this.formData.end_time]
      // console.log(this.formData.start_time)
      // // 弹框打开
      this.flag = true
    },

    // ============================删除
    async onDelete(id) {
      await this.$confirm('确认删除吗')
      // 发送请求
      await delClassApi(id)
      // 信息提示
      this.$message.success('删除成功')
      // 边缘问题，如果不是第一页且该页只有一个删除成功，页码减1再拉取列表
      if (this.formData.page > 1 && this.list.length === 1) {
        this.formData.page--
      }
      // 重新拉取表格
      this.initData()
    },
    changeTime() {
      // this.queryData.start_time = +new Date(this.timeList[0])
      // this.queryData.end_time = +new Date(this.timeList[this.timeList.length - 1])
      this.formData.start_time = moment(this.timeList[0]).utc().format()
      this.formData.end_time = moment(this.timeList[1]).utc().format()
    },
    // 开关转换
    async switchChange(val, id) {
      console.log(val, id) // 1,26
      await getSwitchApi({ state: val, id: id })
      // console.log(res)
      this.$message.success('切换成功')
    },
    // 格式化时间
    formatTime(time) {
      return moment(time).format('YYYY-MM-DD')
    },
    // 获取老师信息
    async getTeacherList() {
      const manager = await getTeacherApi({ role_name: '班主任' })
      // console.log( manager)
      this.manager = manager
      const teacher = await getTeacherApi({ role_name: '讲师' })
      // console.log(teacher)
      this.teacher = teacher
      const zhujiao = await getTeacherApi({ role_name: '助教' })
      // console.log(zhujiao)
      this.zhujiao = zhujiao
    }
  }
}
</script>
<style scoped>
.container-box {
  padding: 30px;
}
.page{
  margin-top: 20px;
}
 .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
